import { IBreadcrumb } from '@/base-ui/breadcrumb'
import { RouteRecordRaw } from 'vue-router'

// 进入页面时首次跳转的菜单
let firstMenu: any = null

export function mapMenusToRouter(userMenus: any[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []

  // 1.加载所有的route
  const allRoutes: RouteRecordRaw[] = []
  const routerFiles = require.context('../router/main', true, /\.ts/)
  routerFiles.keys().forEach((key) => {
    const route = require('../router/main' + key.split('.')[1])
    allRoutes.push(route.default)
  })

  // 2.根据菜单获取需要添加的route
  const _recurseGetRoute = (userMenus: any[]) => {
    for (const menu of userMenus) {
      if (menu.type === 2) {
        const route = allRoutes.find((route) => menu.url === route.path)
        if (route) routes.push(route)
        if (!firstMenu) {
          firstMenu = route
        }
      } else {
        _recurseGetRoute(menu.children)
      }
    }
  }
  _recurseGetRoute(userMenus)

  return routes
}

export function mapPathToMenu(
  userMenus: any[],
  currentPath: string,
  Breadcrumbs?: any[]
): any {
  for (const menu of userMenus) {
    if (menu.type === 1) {
      const menu_second = mapPathToMenu(menu.children ?? [], currentPath)
      if (menu_second) {
        Breadcrumbs?.push({ name: menu.name, path: menu.path })
        Breadcrumbs?.push({ name: menu_second.name, path: menu_second.path })
        return menu_second
      }
    } else if (menu.type === 2 && menu.url === currentPath) {
      return menu
    }
  }
}

export function mapPathToBreadcrumbs(
  userMenus: any[],
  currentPath: string
): any {
  const breadcrumbs: IBreadcrumb[] = []
  mapPathToMenu(userMenus, currentPath, breadcrumbs)
  return breadcrumbs
}

export function mapMenusToPermission(userMenus: any[]) {
  const permissions: string[] = []

  const _recurseGetPermission = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 1 || menu.type === 2) {
        _recurseGetPermission(menu.children ?? [])
      } else if (menu.type === 3) {
        permissions.push(menu.permission)
      }
    }
  }
  _recurseGetPermission(userMenus)
  return permissions
}

export function menuMapLeafKeys(menuList: any) {
  const leafKeys: number[] = []

  const _recurseGetLeaf = (menuList: any) => {
    for (const item of menuList) {
      if (item.children) {
        _recurseGetLeaf(item.children)
      } else {
        leafKeys.push(item.id)
      }
    }
  }
  _recurseGetLeaf(menuList)
  return leafKeys
}

export { firstMenu }
